#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
使用本地配置启动媒体服务
"""
import os
import sys
from configs.global_config import global_config
from flask_server import app, register_to_nacos, deregister_from_nacos
import atexit
import signal

def start_service():
    """启动服务"""
    # 加载本地配置
    config_path = "configs/local_22_config.json"
    
    if not os.path.exists(config_path):
        print(f"错误: 配置文件 {config_path} 不存在")
        sys.exit(1)
    
    print(f"正在加载配置文件: {config_path}")
    global_config.initialize(config_path=config_path)
    
    # 获取服务配置
    listen_host = global_config.get("service.listen_host", "0.0.0.0")
    port = global_config.get("service.port", 5555)
    debug = global_config.get("service.debug", False)
    
    print(f"服务将启动在 {listen_host}:{port}")
    print(f"调试模式: {debug}")
    print(f"离线模式: {global_config.get('clip.offline_mode', False)}")
    print(f"本地模型路径: {global_config.get('clip.local_model_path', '未设置')}")
    
    # 注册到Nacos
    register_to_nacos()
    
    # 注册退出处理函数
    atexit.register(deregister_from_nacos)
    
    def signal_handler(sig, frame):
        print("\n接收到终止信号，正在关闭服务...")
        deregister_from_nacos()
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    print("正在启动服务...")
    try:
        app.run(host=listen_host, port=port, debug=debug, threaded=True)
    except Exception as e:
        print(f"服务启动失败: {str(e)}")
        deregister_from_nacos()

if __name__ == "__main__":
    start_service()